import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { OrderOrderEntity } from '../entity/order';
import { OrderGoodsEntity } from '../entity/goods';
import { PluginService } from '../../plugin/service/info';
import { UserInfoEntity } from '../../user/entity/info';
import { OrderShopEntity } from '../entity/shop';
import { AppointmentInfoEntity } from '../../appointment/entity/info';
import { OrderShareEntity } from '../entity/share';
import { OrderMerchantEntity } from '../entity/merchant';
import { OrderQualityEntity } from '../entity/quality';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { BaseSysUserRoleEntity } from '../../base/entity/sys/user_role';
import { AgentRelationService } from '../../agent/service/agent';
import * as fs from 'fs';
import * as path from 'path';
import moment = require('moment');
import { time } from 'console';
import { OrderRefundEntity } from '../entity/refund';
import axios from 'axios';
const crypto = require('crypto');

/**
 * 订单服务
 */
@Provide()
export class OrderOrderService extends BaseService {
  @InjectEntityModel(OrderOrderEntity)
  orderOrderEntity: Repository<OrderOrderEntity>;

  @InjectEntityModel(OrderGoodsEntity)
  orderGoodsEntity: Repository<OrderGoodsEntity>;

  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;

  @InjectEntityModel(OrderShopEntity)
  orderShopEntity: Repository<OrderShopEntity>;

  @InjectEntityModel(AppointmentInfoEntity)
  appointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(OrderShareEntity)
  orderShareEntity: Repository<OrderShareEntity>;

  @InjectEntityModel(OrderMerchantEntity)
  orderMerchantEntity: Repository<OrderMerchantEntity>;

  @InjectEntityModel(OrderQualityEntity)
  orderQualityEntity: Repository<OrderQualityEntity>;

  @InjectEntityModel(OrderRefundEntity)
  orderRefundEntity: Repository<OrderRefundEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @InjectEntityModel(BaseSysUserRoleEntity)
  baseSysUserRoleEntity: Repository<BaseSysUserRoleEntity>;

  @Inject()
  agentRelationService: AgentRelationService;

  @Inject()
  pluginService: PluginService;

  @Inject()
  ctx;

  // 重写page函数
  async page(query, options) {
    // 判断是否传有二级代理商
    // 判断是否传有一级代理商
    if (query.secondAgentId) {
      const shopIds = await this.agentRelationService.getAgentShopIdsByAgentId(query.secondAgentId);
      console.log('shopIds', shopIds);
      if (shopIds.length > 0) {
        query.shopId = shopIds;
      } else {
        query.shopId = [0];
      }
    } else if (query.firstAgentId) {
      const shopIds = await this.agentRelationService.getAgentShopIdsByAgentId(query.firstAgentId);
      console.log('shopIds', shopIds);
      if (shopIds.length > 0) {
        query.shopId = shopIds;
      } else {
        query.shopId = [0];
      }
    }
    console.log('query', query);
    // 调用父类的page方法
    const res = await super.page(query, options);
    // 如果是path参数则拼接代理商数据
    if (query.path === 'orderTongKang') {
      // 获取店铺的一级和二级代理商
      const shopAgentMap = await this.agentRelationService.orderShopAgentMap();
      // 拼接一级代理商数据
      res.list.map(item => {
        const shop = shopAgentMap.find(shopItem => shopItem.id === item.shopId);
        if (shop) {
          item.agentId = shop.agentUserId;
          item.agentName = shop.agentName;
        }
      })
    }
    
    return res;
  }

  // 获取已支付完成的订单
  async getPaidOrders() {
    const order = await this.orderOrderEntity.find({
      where: {
        payStatus: 1,
        userId: this.ctx.user.id,
      },
    });
    const orderList = [];
    // 遍历拼接订单上的商品信息
    for (const item of order) {
      const goodIds = item.GoodIds.split(',');
      const goods = await this.orderGoodsEntity.find({
        where: {
          id: In(goodIds),
        },
      });
      // 由于 OrderOrderEntity 上不存在 goodsInfo 属性，我们可以使用类型断言创建一个临时对象来保存商品信息
      const orderWithGoods = {
        ...item,
        goodsInfo: goods,
      } as OrderOrderEntity & { goodsInfo: OrderGoodsEntity[] };
      orderList.push(orderWithGoods);
    }
    return orderList;
  }

  // 按钮鉴权
  async createOrderBackendAuth() {
    // 判断是否有后台管理权限
    const adminId = this.ctx.admin.userId;
    // 查看是否有id9的权限
    const adminRole = await this.baseSysUserRoleEntity.findOne({
      where: {
        userId: adminId,
        roleId: 9,
      },
    });
    if (adminId == 1) {
      return true;
    }
    console.log('createOrderBackendAuth', adminId, adminRole);
    if (!adminRole) {
      return false;
    }
    return true;
  }

  // 后台根据用户名手机号商品ID创建订单
  async createOrderBackend(params) {
    // 抛出当前时间戳
    console.log(params);
    const adminId = this.ctx.admin.userId;
    const admin = await this.baseSysUserEntity.findOne({
      where: {
        id: adminId,
      },
    });
    if (!admin.shopId || admin.shopId === 0) {
      throw new Error('请联系管理员绑定店铺');
    }
    let shopId = admin.shopId;

    // 如果参数有店铺id则以参数为准
    if (params.shopId) {
      shopId = params.shopId;
    }

    const { userName, userPhone, goodsMoney, payImg, eyeglassImg } = params;
    if (!userName || !userPhone || !goodsMoney || !payImg) {
      throw new Error('请填写完整的信息');
    }

    if (!eyeglassImg) {
      throw new Error('请上传电脑验光单,用户才可以享受183天上涨50度免费更换的服务');
    }

    // 检查手机号是否符合格式
    if (!/^1[3456789]\d{9}$/.test(userPhone)) {
      throw new Error('手机号格式错误');
    }

    const goods = await this.orderGoodsEntity.findOne({
      // where: {
      //   id: goodsId,
      // },
      where: {
        goodsPrice: goodsMoney,
      },
    });
    console.log(goods);
    if (!goods) {
      throw new Error('商品不存在');
    }

    let user = await this.userInfoEntity.findOne({
      where: {
        phone: userPhone,
      },
    });

    // 没有用户则创建用户
    if (!user) {
      user = new UserInfoEntity();
      user.phone = userPhone;
      user.nickName = userName;
      user.shopId = shopId;
      user.openid = '';
      await this.userInfoEntity.save(user);
    } else {
      user.nickName = userName;
      user.shopId = shopId;
      await this.userInfoEntity.save(user);
    }

    // 新建订单
    const order = new OrderOrderEntity();
    order.orderNo = moment().format('YYMMDDHHmmssSSS');
    order.userId = user.id;
    order.GoodIds = goods.id.toString();
    order.payStatus = 1;
    order.totalAmount = goods.goodsPrice;
    order.payAmount = goods.goodsPrice;
    order.shopId = shopId;
    order.adminId = adminId;
    order.payType = 1; // 后台支付
    order.payImg = payImg;
    order.eyeglassImg = eyeglassImg;
    order.lensQuantity = params.lensQuantity;
    await this.orderOrderEntity.save(order);
    return true;
  }

  // 后台根据用户名手机号商品ID创建客情订单
  async createCustomerOrderBackend(params) {
    // 抛出当前时间戳
    console.log(params);
    const adminId = this.ctx.admin.userId;
    let shopId = 0;

    // 如果参数有店铺id则以参数为准
    if (params.shopId) {
      shopId = params.shopId;
    }

    if (shopId === null || shopId === 0) {
      throw new Error('店铺不能为空');
    }

    const { userName, userPhone, goodsMoney, payImg, eyeglassImg } = params;
    if (!userName || !userPhone || !goodsMoney || !payImg) {
      throw new Error('请填写完整的信息');
    }

    if (!eyeglassImg) {
      throw new Error('请上传电脑验光单,用户才可以享受183天上涨50度免费更换的服务');
    }

    // 检查手机号是否符合格式
    if (!/^1[3456789]\d{9}$/.test(userPhone)) {
      throw new Error('手机号格式错误');
    }

    const goods = await this.orderGoodsEntity.findOne({
      // where: {
      //   id: goodsId,
      // },
      where: {
        goodsPrice: goodsMoney,
      },
    });
    console.log(goods);
    if (!goods) {
      throw new Error('商品不存在');
    }

    let user = await this.userInfoEntity.findOne({
      where: {
        phone: userPhone,
      },
    });

    // 没有用户则创建用户
    if (!user) {
      user = new UserInfoEntity();
      user.phone = userPhone;
      user.nickName = userName;
      user.shopId = shopId;
      user.openid = '';
      await this.userInfoEntity.save(user);
    } else {
      user.nickName = userName;
      user.shopId = shopId;
      await this.userInfoEntity.save(user);
    }

    // 新建订单
    const order = new OrderOrderEntity();
    order.orderNo = moment().format('YYMMDDHHmmssSSS');
    order.userId = user.id;
    order.GoodIds = goods.id.toString();
    order.payStatus = 1;
    order.totalAmount = goods.goodsPrice;
    order.payAmount = goods.goodsPrice;
    order.shopId = shopId;
    order.adminId = adminId;
    order.payType = 1; // 后台支付
    order.lensQuantity = params.lensQuantity;
    order.payImg = payImg;
    order.eyeglassImg = eyeglassImg;
    order.orderType = 'customerOrder'; // 客情订单
    await this.orderOrderEntity.save(order);
    return true;
  }

  // 根据商品id创建订单并返回订单ID
  async createOrderByGoodsIds(goodsIds: number[], shopId?: number) {
    if (!this.ctx.user.id) {
      throw new Error('亲，请先登录');
    }
    // 检查用户是否有门店ID
    const user = await this.userInfoEntity.findOne({
      where: {
        id: this.ctx.user.id,
      },
    });
    const appoint = await this.appointmentInfoEntity.findOne({
      where: {
        studentId: this.ctx.user.id,
      },
    });

    if (!appoint) {
      throw new Error('请先预约门店');
    }
    if (!shopId) {
      shopId = user.shopId || 0;
    }

    // 检查店铺是否有配置merchanid
    // await this.getShopMerchantConfig(shopId);
    const goods = await this.orderGoodsEntity.find({
      where: {
        id: In(goodsIds),
      },
    });
    if (!goods) {
      throw new Error('商品不存在');
    }
    if (!user.openid) {
      throw new Error('请先绑定微信');
    }
    // 2. 创建订单
    const order = new OrderOrderEntity();
    // order.orderNo = await this.pluginService.invoke('pay-wx', 'createOrderNum');
    order.orderNo = moment().format('YYMMDDHHmmssSSS');
    order.userId = this.ctx.user.id;
    order.GoodIds = goodsIds.join(',');
    order.totalAmount = goods.reduce(
      (total, item) => total + item.goodsPrice,
      0
    );
    order.payAmount = order.totalAmount;
    order.shopId = shopId;
    order.adminId = user.registAdminId;
    await this.orderOrderEntity.save(order);
    return order.id;
  }

  // 根据商品id创建订单并返回订单ID  购买商品或升级商品
  async createOrderBuyOrUpGoods(body: { goodsIds: string; shopId?: number; filmCode?: string; lensQuantity?: number }) {
    const goodsIds = body.goodsIds;
    let shopId = body.shopId;
    console.log(body);
    if (!this.ctx.user.id) {
      throw new Error('亲，请先登录');
    }
    // 检查用户是否有门店ID
    const user = await this.userInfoEntity.findOne({
      where: {
        id: this.ctx.user.id,
      },
    });

    const appoint = await this.appointmentInfoEntity.findOne({
      where: {
        studentId: this.ctx.user.id,
      },
    });

    if (!appoint) {
      throw new Error('请先预约门店');
    }
    if (!shopId) {
      shopId = user.shopId;
    }

    // 检查店铺是否有配置merchanid
    await this.getShopMerchantConfig(shopId);
    const goodsRes = await this.orderGoodsEntity.find();
    const goodsMap = goodsRes.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});
    let goods = goodsMap[goodsIds];

    console.log(goods);

    if (!goodsRes) {
      throw new Error('商品不存在');
    }
    if (!user.openid) {
      throw new Error('请先绑定微信');
    }
    // 2. 创建订单
    const order = new OrderOrderEntity();
    // order.orderNo = await this.pluginService.invoke('pay-wx', 'createOrderNum');
    order.orderNo = moment().format('YYMMDDHHmmssSSS');
    order.userId = this.ctx.user.id;
    order.GoodIds = goodsIds;
    // order.totalAmount = goods.switchList.data.reduce(
    //   (total, item) => total + item.goodsPrice,
    //   0
    // );
    order.totalAmount = goods.goodsPrice;
    order.payAmount = order.totalAmount;
    order.shopId = shopId;
    order.adminId = user.registAdminId;
    order.lensCode = body.filmCode;
    order.lensQuantity = body.lensQuantity;
    console.log(order);
    await this.orderOrderEntity.save(order);
    return order.id;
  }

  // 检查店铺是否有配置merchanid
  async getShopMerchantConfig(shopId: number) {
    const shop = await this.orderShopEntity.findOne({
      where: {
        id: shopId,
      },
    });
    if (!shop) {
      throw new Error('亲，请先选择门店');
    }
    if (!shop.payMerchantId) {
      throw new Error('该门店暂不支持支付');
    }
    const merchant = await this.orderMerchantEntity.findOne({
      where: {
        id: shop.payMerchantId,
      },
    });
    if (!merchant) {
      throw new Error('该门店暂不支持支付');
    }
    if (!merchant.merchantPayParams) {
      throw new Error('该门店暂不支持支付');
    }
    // merchant.merchantPayParams.privateKey = 'D:/tongRenProject/apiclient_key.pem'; // 私钥
    // merchant.merchantPayParams.publicKey = 'D:/tongRenProject/apiclient_cert.pem'; // 证书
    // merchant.merchantPayParams.verifyPublicKey = 'D:/tongRenProject/apiclient_cert.p12';
    // const rootDir = path.resolve(__dirname, '../../../');
    // merchant.merchantPayParams.publicKey = merchant.merchantPayParams.publicKey.replace('@baseDir', rootDir);
    // merchant.merchantPayParams.privateKey = merchant.merchantPayParams.privateKey.replace('@baseDir', rootDir);
    // merchant.merchantPayParams.verifyPublicKey = merchant.merchantPayParams.verifyPublicKey.replace('@baseDir', rootDir);
    return merchant.merchantPayParams;
  }

  // 根据订单ID获取订单详情
  async getOrderInfo(orderId: number) {
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: orderId,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    }
    const goodIds = order.GoodIds.split(',');
    const goods = await this.orderGoodsEntity.find({
      where: {
        id: In(goodIds),
      },
    });

    const shop = await this.orderShopEntity.findOne({
      where: {
        id: order.shopId,
      },
    });
    let shopName = '请选择店铺';
    if (shop) {
      order.shopId = shop.id;
      shopName = shop.name;
    } else {
        // 查找最近预约的门店
      const appoint = await this.appointmentInfoEntity.findOne({
        where: {
          studentId: this.ctx.user.id,
        },
        order: {
          appointmentTime: 'DESC',
        },
      });
      if (appoint) {
        const shop = await this.orderShopEntity.findOne({
          where: {
            id: appoint.shopId,
          },
        });
        if (shop) {
          order.shopId = shop.id;
          shopName = shop.name;
        }
      }
    }

    // 拼接上名字给订单
    const orderWithShopName = { ...order, shopName: shopName };

    const subTitle = ['服务：183天上涨超过50度免费换新', ''];
    return {
      orderInfo: orderWithShopName,
      goodInfo: goods,
      subTitle: subTitle,
    };
  }

  // 根据订单ID获取微信支付参数
  async getPayParams(orderId: number, shopId: number) {
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: orderId,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    }
    if (order.miniPayParams) {
      return order.miniPayParams;
    }

    if (shopId != 0) {
      order.shopId = shopId;
      await this.orderOrderEntity.save(order);
    }

    if (!order.shopId) {
      throw new Error('请先选择门店');
    }

    // 检查店铺是否有配置merchanid
    const merchantPayParams = await this.getShopMerchantConfig(order.shopId);
    console.log('merchantPayParams', merchantPayParams);
    if (!merchantPayParams) {
      throw new Error('该门店暂不支持支付');
    }

    const user = await this.userInfoEntity.findOne({
      where: {
        id: this.ctx.user.id,
      },
    });
    if (!user.openid) {
      throw new Error('请先绑定微信');
    }
    // 获得插件实例
    const plugin = await this.pluginService.getInstance('pay-wx');
    // 获得微信支付 SDK 实例
    const instance = await plugin['getInstance'](merchantPayParams);
    let payTotal = order.totalAmount * 100;
    if (user.phone == '13317640150') {
      payTotal = 15;
    }
    console.log('支付参数', merchantPayParams);
    console.log('回调地址', merchantPayParams.notify_url);
    const params = {
      description: '商品订单',
      out_trade_no: order.orderNo,
      notify_url: merchantPayParams.notify_url,
      amount: {
        total: payTotal,
      },
      payer: {
        openid: user.openid,
      },
      scene_info: {
        payer_client_ip: 'ip',
      },
      settle_info: {
        profit_sharing: true,
      },
    };
    const result = await instance.transactions_jsapi(params);
    console.log(result, params, payTotal, this.ctx.user.phone);
    if (result.status != 200) {
      throw new Error(result.message);
    }
    order.miniPayParams = result.data;
    await this.orderOrderEntity.save(order);
    return result.data;
  }

  async handleWxPayNotify(body, shopId = 0) {
    try {
      console.log('收到微信支付回调:', body);
      // 获得插件实例
      const plugin = await this.pluginService.getInstance('pay-wx');
      // 根据shopId获取对应的店铺配置
      let shopConfig = await this.getShopMerchantConfig(shopId);

      // 获得微信支付 SDK 实例，传入对应店铺的配置
      const instance = await plugin['getInstance'](shopConfig);

      const { ciphertext, associated_data, nonce } = body.resource;
      const data: any = instance.decipher_gcm(
        ciphertext,
        associated_data,
        nonce
      );
      console.log('解密后的回调数据:', shopConfig, data);
      // 验签通过，处理业务逻辑
      if (data.trade_state == 'SUCCESS') {
        // 查询订单
        const order = await this.orderOrderEntity.findOne({
          where: { orderNo: data.out_trade_no },
        });

        if (order) {
          // 更新订单状态
          await this.orderOrderEntity.update(order.id, {
            payStatus: 1,
            payTime: new Date(),
            transactionId: data.transaction_id,
            updateTime: new Date(),
          });
        }
        // 支付成功后进行分账
        // await this.shareOrder(order.id);
      }
      return 'success';
    } catch (error) {
      console.error('处理微信支付回调出错:', error);
      return 'fail';
    }
  }

  // 添加分账接收方
  async addShareReceiver(merchant_id) {
    const merchant = await this.orderMerchantEntity.findOne({
      where: {
        id: merchant_id,
      },
    });
    if (!merchant) {
      throw new Error('商户不存在');
    }
    // 查看商户有没有填写参数
    if (!merchant.merchantPayParams) {
      throw new Error('该门店暂不支持支付');
    }

    // 获得插件实例
    const plugin = await this.pluginService.getInstance('pay-wx');
    const rootDir = path.resolve(__dirname, '../../../');
    // 将参数里面的路径中@baseDir的路径替换为rootDir
    const config = await plugin['getConfig']();
    merchant.merchantPayParams.publicKey =
      merchant.merchantPayParams.publicKey.replace('@baseDir', rootDir);
    merchant.merchantPayParams.privateKey =
      merchant.merchantPayParams.privateKey.replace('@baseDir', rootDir);
    merchant.merchantPayParams.verifyPublicKey =
      merchant.merchantPayParams.verifyPublicKey.replace('@baseDir', rootDir);
    // 获得微信支付 SDK 实例
    const instance = await plugin['getInstance'](merchant.merchantPayParams);
    let certificate = {
      publicKey: '',
      serial_no: '',
    };
    if (merchant.merchantPayParams.isApiCert) {
      console.log('获取证书', merchant.merchantPayParams.key, instance);
      const certificates = await instance.get_certificates(
        merchant.merchantPayParams.key
      );
      console.log('获取证书数组', certificates);
      certificate = certificates.pop();
      console.log('获取证书', certificate.publicKey);
    } else {
      // 根据文件读取解析
      const publicKey = fs.readFileSync(
        merchant.merchantPayParams.publicKeyPath,
        'utf8'
      );
      certificate = {
        publicKey: publicKey,
        serial_no: merchant.merchantPayParams.publicKeyString,
      };
    }

    console.log('路径解析', certificate);
    // 读取微信支付公钥内容
    // console.log(name)
    // const params = {
    //   appid: 'wx6b01843d1f2874b8',
    //   type: 'MERCHANT_ID',
    //   account: '1726809145',
    //   name: instance.publicEncrypt(
    //     '北京瞳康科技文化有限公司',
    //     certificate.publicKey
    //   ),
    //   // name: instance.publicEncrypt('北京瞳康科技文化有限公司', publicKey),
    //   relation_type: 'SUPPLIER',
    //   custom_relation: '供应商',
    //   wx_serial_no: certificate.serial_no,
    //   // wx_serial_no: merchant.merchantPayParams.publicKeyString
    // };
    // const res1 = await instance.profitsharing_receivers_add(params);

    const params2 = {
      appid: 'wx6b01843d1f2874b8',
      type: 'MERCHANT_ID',
      account: '1727151117',
      name: instance.publicEncrypt(
        '北京博视爱眼国际贸易有限公司',
        certificate.publicKey
      ),
      relation_type: 'DISTRIBUTOR',
      custom_relation: '分销商',
      wx_serial_no: certificate.serial_no,
    };
    const res2 = await instance.profitsharing_receivers_add(params2);

    // const params3 = {
    //   appid: 'wx6b01843d1f2874b8',
    //   type: 'MERCHANT_ID',
    //   account: '1713344906',
    //   name: instance.publicEncrypt(
    //     '北京双博视网络科技有限公司',
    //     certificate.publicKey
    //   ),
    //   relation_type: 'SERVICE_PROVIDER',
    //   custom_relation: '服务商',
    //   wx_serial_no: certificate.serial_no,
    // };
    // const res3 = await instance.profitsharing_receivers_add(params3);

    // const params4 = {
    //   appid: 'wx6b01843d1f2874b8',
    //   type: 'MERCHANT_ID',
    //   account: '1727270579',
    //   name: instance.publicEncrypt(
    //     '北京听澜互动传媒文化传播有限公司',
    //     certificate.publicKey
    //   ),
    //   relation_type: 'SERVICE_PROVIDER',
    //   custom_relation: '服务商',
    //   wx_serial_no: certificate.serial_no,
    // };
    // const res4 = await instance.profitsharing_receivers_add(params4);

    const params5 = {
      appid: 'wx6b01843d1f2874b8',
      type: 'MERCHANT_ID',
      account: '1728233082',
      name: instance.publicEncrypt(
        '北京凡光',
        certificate.publicKey
      ),
      relation_type: 'DISTRIBUTOR',
      custom_relation: '分销商',
      wx_serial_no: certificate.serial_no,
    };
    const res5 = await instance.profitsharing_receivers_add(params5);

    console.log('添加分账接收方', res2, res5);
  }

  // 根据订单ID进行分账
  async shareOrder(orderId: number) {
    const order = await this.orderOrderEntity.findOne({
      where: {
        id: orderId,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    }

    // 获得插件实例
    const plugin = await this.pluginService.getInstance('pay-wx');
    // 根据订单店铺设置支付
    const merchantPayParams = await this.getShopMerchantConfig(order.shopId);
    if (!merchantPayParams) {
      throw new Error('该门店暂不支持分账');
    }

    // 获得微信支付 SDK 实例
    const instance = await plugin['getInstance'](merchantPayParams);
    // 获得插件配置

    // 2. 创建订单
    // 查看是否已有分账订单
    let shareOrder = await this.orderShareEntity.findOne({
      where: {
        sysOrderId: order.id,
      },
    });
    if (!shareOrder) {
      shareOrder = new OrderShareEntity();
      shareOrder.orderNo = await this.pluginService.invoke(
        'pay-wx',
        'createOrderNum'
      );
      shareOrder.sysOrderId = order.id;
      shareOrder.shareAmount = order.payAmount;
      shareOrder.transactionId = order.transactionId;
      await this.orderShareEntity.save(shareOrder);
    }

    // {
    //     "key": "shbos20250421WechatPayDetailweix",
    //     "appid": "wx6b01843d1f2874b8",
    //     "mchid": "1713344906",
    //     "publicKey": "./cert/apiclient_cert.pem",
    //     "notify_url": "http://tongren.joyballet.cn/api/app/order/order/handleWxPayNotify",
    //     "privateKey": "./cert/apiclient_key.pem",
    //     "verifyPublicKey": "./cert/apiclient_cert.p12"
    // }
    // const certificates = await instance.get_certificates(config.key);
    // const certificates = config.key;
    // 分账配置
    // 门店：2786，支付号：1707547265
    // 瞳康：594，支付号：1726809145，供应商
    // 博视爱眼：360，支付号：1727151117，分销商
    // 北京双博视：240，支付号：1713344906，服务商
    // 根据订单金额进行分账
    const amount = order.payAmount;
    let supplierAmount = Math.floor(amount * 0.3);
    // let distributorAmount = Math.floor(amount * 0.04);
    // let serviceProviderAmount = Math.floor(amount * 0.06);
    // let serviceProviderAmount2 = Math.floor(amount * 0.05);
    // if (order.totalAmount == 3980) {
    //   supplierAmount = 594;
    //   distributorAmount = 160;
    //   serviceProviderAmount = 240;
    //   serviceProviderAmount2 = 200;
    // }
    if (order.userId == 41) {
      supplierAmount = 0.04;
      // distributorAmount = 0.01;
      // serviceProviderAmount = 0.01;
      // serviceProviderAmount2 = 0.01;
    }

    const params = {
      transaction_id: order.transactionId,
      out_order_no: shareOrder.orderNo,
      receivers: [
        // {
        //   type: 'MERCHANT_ID',
        //   account: '1726809145',
        //   amount: supplierAmount * 100,
        //   description: '瞳康',
        // },
        {
          type: 'MERCHANT_ID',
          account: '1727151117',
          amount: supplierAmount * 100,
          description: '博视爱眼'
        },
        // {
        //   type: 'MERCHANT_ID',
        //   account: '1713344906',
        //   amount: serviceProviderAmount * 100,
        //   description: '北京双博视'
        // },
        // {
        //   type: 'MERCHANT_ID',
        //   account: '1727270579',
        //   amount: serviceProviderAmount2 * 100,
        //   description: '北京听澜互动传媒文化传播有限公司'
        // }
      ],
      unfreeze_unsplit: true,
    };
    // 直接调用分账API，不需要手动加密
    const result = await instance.create_profitsharing_orders(params);
    console.log('shareOrder', params, result);
    if (result.status != 200) {
      shareOrder.shareStatus = 2; // 分账失败
      shareOrder.remark = result.errRaw.text;
      await this.orderShareEntity.save(shareOrder);
      throw new Error(result.errRaw.response.text);
    }
    shareOrder.shareStatus = 1; // 分账成功
    await this.orderShareEntity.save(shareOrder);
    return shareOrder.id;
  }

  // 查询激活订单
  async queryActiveOrder(body) {
    console.log('body', body.scanUserId);
    // 查找激活的订单
    const activeOrder = await this.orderQualityEntity.find({
      where: {
        scanUserId: body.scanUserId,
        isActive: 1,
      },
    });

    if (activeOrder.length == 0) {
      throw new Error('您当前没有激活的镜片，请先激活镜片后查询');
    }

    const orders = await this.orderOrderEntity.find({
      where: {
        id: In(activeOrder.map(item => item.orderId)),
      },
    });

    const shop = await this.orderShopEntity.find({
      where: {
        id: In(orders.map(item => item.shopId)),
      },
    });

    // 创建订单ID到店铺ID的映射
    const orderIdToShopId = orders.reduce((acc, order) => {
      acc[order.id] = order.shopId;
      return acc;
    }, {});

    // 创建店铺ID到店铺数据的映射
    const shopIdToShopData = shop.reduce((acc, item) => {
      acc[item.id] = item;
      return acc;
    }, {});

    // 创建订单ID到店铺数据的映射 - 实现orderId:{shop数据}的格式
    const orderShop = orders.reduce((acc, order) => {
      const shopId = order.shopId;
      if (shopId && shopIdToShopData[shopId]) {
        acc[order.id] = shopIdToShopData[shopId];
      }
      return acc;
    }, {});

    const orderOptometrics = orders.reduce((acc, order) => {
      acc[order.id] = order.optometricsData;
      return acc;
    }, {});

    // 查询用户电话
    const user = await this.userInfoEntity.findOne({
      where: {
        id: body.scanUserId,
      },
    });
    const phone = user?.phone || '';
    // phone需要脱敏
    const phoneMask = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');

    const resData = activeOrder.map(item => ({
      ...item,
      optometrics: orderOptometrics[item.orderId],
      shopName: orderShop[item.orderId].name,
      expireTime: new Date(new Date(item.updateTime).setDate(new Date(item.updateTime).getDate() + 183)),
      phone: phoneMask,
    }));

    return resData;
  }

  async activeOrder({ name, birthDate, gender, scanLeft, scanRight }) {
    // const [orderNo, eyeLeft] = scanLeft.split('-');
    // const [orderNo2, eyeRight] = scanRight.split('-');
    // 将scanString截取前面16位作为订单号，长度倒数1位作为eye
    const eyeLeft = scanLeft.substring(scanLeft.length - 1, scanLeft.length);
    const orderNo = scanLeft.substring(0, 15);

    const eyeRight = scanRight.substring(scanRight.length - 1, scanRight.length);
    const orderNo2 = scanRight.substring(0, 15);

    if (orderNo !== orderNo2) {
      throw new Error('亲，请重新扫描一下镜片二维码');
    }
    if (eyeLeft !== 'L' || eyeRight !== 'R') {
      throw new Error('亲，请重新扫描一下镜片二维码～');
    }
    
    // 查找是否有激活的
    const scanLeftActive = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye: eyeLeft,
        // scanUrl: scanLeft,
        isActive: 1,
      },
    });
    // 查找是否有激活的
    const scanRightActive = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye: eyeRight,
        // scanUrl: scanRight,
        isActive: 1,
      },
    });
    if (scanLeftActive && scanRightActive) {
      throw new Error('镜片都已激活');
    }
    if (scanLeftActive) {
      throw new Error('左镜片已激活');
    }
    if (scanRightActive) {
      throw new Error('右镜片已激活');
    }
    // 激活镜片
    const scanLeftNoActive = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye: eyeLeft,
        // scanUrl: scanLeft,
        scanUserId: this.ctx.user.id,
        isActive: 0,
      },
    });
    if (!scanLeftNoActive) {
      throw new Error('请重新扫码左镜片后点确认');
    }
    scanLeftNoActive.isActive = 1;
    scanLeftNoActive.name = name;
    scanLeftNoActive.birthDate = birthDate;
    scanLeftNoActive.sex = gender;
    await this.orderQualityEntity.save(scanLeftNoActive);
    // 激活右镜片
    const scanRightNoActive = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye: eyeRight,
        // scanUrl: scanRight,
        scanUserId: this.ctx.user.id,
        isActive: 0,
      },
    });
    if (!scanRightNoActive) {
      throw new Error('请重新扫描又镜片后点确认');
    }
    scanRightNoActive.isActive = 1;
    scanRightNoActive.name = name;
    scanRightNoActive.birthDate = birthDate;
    scanRightNoActive.sex = gender;
    await this.orderQualityEntity.save(scanRightNoActive);

    return {
      scanLeftNoActive,
      scanRightNoActive,
    };
  }

  // 检查scanUrl
  async checkScanUrl(scanUrl: string) {
    // 将scanString用-分隔开，前面是订单号，后面是字母L/R识别左右
    try {
      // const [orderNo, eye] = scanUrl.split('-');
      // 将scanString截取前面16位作为订单号，长度倒数1位作为eye
      const eye = scanUrl.substring(scanUrl.length - 1, scanUrl.length);
      const orderNo = scanUrl.substring(0, 15);
      
      const order = await this.orderOrderEntity.findOne({
        where: {
          orderNo,
        },
      });
      console.log('scanUrl', scanUrl, orderNo, eye, order);
      if (!order) {
        throw new Error(
          '验证失败！该防伪码无效，认准官方授权渠道，谨防假冒产品'
        );
      }
      if (eye != 'L' && eye != 'R') {
        throw new Error(
          '验证失败！该防伪码无效，认准官方授权渠道，谨防假冒产品'
        );
      }
      // 查看是否已经激活过了
      // const scan = await this.orderQualityEntity.findOne({
      //   where: {
      //     orderNo,
      //     eye,
      //     scanUrl,
      //     isActive: 1,
      //   }
      // });
      // if (scan) {
      //   throw new Error('该镜片已经激活过了，无法再激活');
      // }

      return true;
    } catch (e) {
      throw new Error(e.message);
    }
  }

  // 根据订单ID获取订单信息
  async getOrderById(scanUrl: string) {
    // 将scanString用-分隔开，前面是订单号，后面是字母L/R识别左右
    // const [orderNo, eye] = scanUrl.split('-');
    const eye = scanUrl.substring(scanUrl.length - 1, scanUrl.length);
    const orderNo = scanUrl.substring(0, 15);
    const order = await this.orderOrderEntity.findOne({
      where: {
        orderNo,
      },
    });
    if (!order) {
      throw new Error('订单不存在');
    }
    // 查看是否已经有了扫描状态
    const scan = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye,
        scanUrl,
        isActive: 1,
      },
    });
    let isActive = 0;
    if (scan) {
      isActive = 1;
    }
    console.log(this.ctx.user);
    // 新增扫描状态
    let scanUser = await this.orderQualityEntity.findOne({
      where: {
        orderNo,
        eye,
        scanUserId: this.ctx.user.id,
      },
    });
    if (!scanUser) {
      scanUser = new OrderQualityEntity();
    }
    scanUser.orderId = order.id;
    scanUser.orderNo = orderNo;
    scanUser.eye = eye;
    scanUser.scanUserId = this.ctx.user.id;
    scanUser.scanUrl = scanUrl;
    // scanUser.scanUrl = orderNo + '-' + eye;
    await this.orderQualityEntity.save(scanUser);

    const shop = await this.orderShopEntity.findOne({
      where: {
        id: order.shopId,
      },
    });

    let orderInfo = {};
    // 解析optometricsData为对象
    const optometricsData =
      typeof order.optometricsData === 'string'
        ? JSON.parse(order.optometricsData)
        : order.optometricsData || {};

    orderInfo = {
      eye: eye === 'L' ? '左眼镜片' : '右眼镜片',
      isActive: isActive == 0 ? '未激活' : '已激活',
      activeColor: isActive == 0 ? 'red' : 'green',
      date: order.createTime
        ? moment(order.createTime).format('YYYY-MM-DD')
        : '', // 转为xxxx-xx-xx模式
      shopName: shop.name,
      // optometricsData: order.optometricsData,
      // 添加所需的镜片参数
      c_diar: optometricsData.c_diar || '',
      c_dial: optometricsData.c_dial || '',
      c_rball: optometricsData.c_rball || '',
      c_lball: optometricsData.c_lball || '',
      c_rpole: optometricsData.c_rpole || '',
      c_lpole: optometricsData.c_lpole || '',
      c_radd: optometricsData.c_radd || '',
      c_ladd: optometricsData.c_ladd || '',
      c_rline: optometricsData.c_rline || '',
      c_lline: optometricsData.c_lline || '',
      pd_r: optometricsData.pd_r || '',
      pd_l: optometricsData.pd_l || '',
      ph_r: optometricsData.ph_r || '',
      ph_l: optometricsData.ph_l || '',
      c_process_type_name: optometricsData.c_process_type_name || '',
      c_coating_type_name: optometricsData.c_coating_type_name || '',
    };

    return orderInfo;
  }

  //根据商品id查询商品信息
  async getGoodsById(goodsId: number) {
    const goods = await this.orderGoodsEntity.findOne({
      where: {
        id: goodsId,
      },
    });
    if (!goods) {
      throw new Error('商品不存在');
    }
    return goods;
  }

  // 逻辑删除
  async delete(ids: any): Promise<void> {
    // 如果ids是单个id，转换为数组
    const idArray = Array.isArray(ids) ? ids : [ids];

    // 遍历所有id，执行逻辑删除
    for (const id of idArray) {
      const order = await this.orderOrderEntity.find({
        where: {
          id,
        },
      });
      let orderList = order.map(item => {
        item.isDeleted = true;
        return item;
      });
      await this.orderOrderEntity.save(orderList);
    }
  }

  // 分账订单详情
  async getShareOrderDetail(body) {
    console.log(body);
    const orderShare = await this.orderShareEntity.findOne({
      where: {
        sysOrderId: body.orderId,
        shareStatus: 2,
      },
    });
    let shopId = null;
    if (!orderShare) {
      throw new Error('分账订单不存在');
    } else {
      const order = await this.orderOrderEntity.findOne({
        where: {
          id: orderShare.sysOrderId,
        },
      });
      shopId = order.shopId;
    }
    // 获得插件实例
    const plugin = await this.pluginService.getInstance('pay-wx');
    const merchantPayParams = await this.getShopMerchantConfig(shopId);
    // merchantPayParams.privateKey = 'D:/tongRenProject/apiclient_key.pem'; // 私钥
    // merchantPayParams.publicKey = 'D:/tongRenProject/apiclient_cert.pem'; // 证书
    // merchantPayParams.verifyPublicKey = 'D:/tongRenProject/apiclient_cert.p12';
    console.log('证书配置:', merchantPayParams);

    // 使用正确的参数名
    const params = {
      // out_order_no: '20250911180400093689338122',
      // transaction_id: '4200002847202509117234519367',
      out_order_no: orderShare.orderNo,
      transaction_id: orderShare.transactionId,
    };
    console.log('查询参数:', params);

    // 获得微信支付 SDK 实例
    const instance = await plugin['getInstance'](merchantPayParams);
    // const res = await instance.query_profitsharing_orders(params);
    const res = await instance.query_profitsharing_orders(
      params.transaction_id,
      params.out_order_no
    );
    console.log('查询结果:', res.data);
    if (res.status == 404) {
      console.log('查询结果:', res);
      console.log('请求地址:', res.errRaw.response.req.url);
      return res;
    } else {
      return res.data;
    }
  }

  // 定时保存订单分账详情
  async getShareOrderDetailTiming() {
    const orderShare = await this.orderShareEntity
      .createQueryBuilder('s')
      .select([
        's.sysOrderId',
        'shop.name',
        's.transactionId as transactionId',
        's.orderNo as wxOrderNo',
        'o.orderNo',
        'shop.id as shopId',
        'shop.payMerchantId as payMerchantId',
      ])
      .leftJoin('order_order', 'o', 'o.id = s.sysOrderId')
      .leftJoin('order_shop', 'shop', 'shop.id = o.shopId')
      .where('s.shareDetail IS NULL')
      .getRawMany();

    // console.log('待查询分账订单:', orderShare);
    if (!orderShare) {
      throw new Error('无待查询分账订单');
    }

    // const shopIds = orderShare.map(item => item.shopId);
    // console.log('shopIds:', shopIds);

    const payMerchantIds = orderShare.map(item => item.payMerchantId);
    // console.log('payMerchantIds:', payMerchantIds);

    const merchantList = await this.orderMerchantEntity.find({
      where: {
        id: In(payMerchantIds),
      },
    });
    // console.log('merchantList:', merchantList);
    // 将merchantList转换为以id为键的对象映射
    let merchantPayParamsList = merchantList.reduce((map, merchant) => {
      map[merchant.id] = merchant;
      return map;
    }, {});
    // console.log('merchantPayParamsList:', merchantPayParamsList);

    for (const item of orderShare) {
      const merchant = merchantPayParamsList[item.payMerchantId];
      if (!merchant) {
        continue;
      }
      console.log('merchantPayParams:', merchant.merchantPayParams);

      // 获得插件实例
      const plugin = await this.pluginService.getInstance('pay-wx');

      merchant.merchantPayParams.privateKey =
        'D:/tongRenProject/apiclient_key.pem'; // 私钥
      merchant.merchantPayParams.publicKey =
        'D:/tongRenProject/apiclient_cert.pem'; // 证书
      merchant.merchantPayParams.verifyPublicKey =
        'D:/tongRenProject/apiclient_cert.p12';
      console.log('证书配置:', merchant.merchantPayParams);

      // 使用正确的参数名
      const params = {
        // out_order_no: '20250911180400093689338122',
        // transaction_id: '4200002847202509117234519367',
        out_order_no: item.wxOrderNo,
        transaction_id: item.transactionId,
      };
      console.log('查询参数:', params);

      // 获得微信支付 SDK 实例
      const instance = await plugin['getInstance'](merchant.merchantPayParams);
      // const res = await instance.query_profitsharing_orders(params);
      // 创建延迟函数（避免频繁请求）
      const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

      let retryCount = 0;
      let finalRes = null;

      // 实现最多三次重试逻辑
      while (retryCount < 3) {
        const res = await instance.query_profitsharing_orders(
          params.transaction_id,
          params.out_order_no
        );
        console.log(`查询结果(尝试${retryCount + 1}/3):`, res);

        if (res == undefined || res == null) {
          console.log('查询结果为空，跳过该订单，订单号有问题');
          break;
        }

        finalRes = res;

        if (res.status == 404) {
          console.log('请求地址:', res.errRaw.response.req.url);
          retryCount++;

          if (retryCount < 3) {
            // 重试前的延迟
            const retryDelay = 5000 + Math.random() * 5000;
            console.log(
              `404错误,${retryDelay / 1000}秒后重试(${retryCount}/3)...`
            );
            await sleep(retryDelay);
          }
        } else {
          // 成功响应，无需重试
          // 根据orderNo更新分账详情
          await this.orderShareEntity.update(
            { orderNo: res.data.out_order_no },
            { shareDetail: res.data }
          );
          break;
        }
      }

      // 最终延迟
      const delayTime = 5000 + Math.random() * 5000;
      console.log(`等待 ${(delayTime / 1000).toFixed(2)} 秒...`);
      await sleep(delayTime);
    }
  }
}
